package com.jinke.uang.ui.activity.validation;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.adapter.OtherAdapter;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.AuthModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.AuthUserInfoData;
import com.jinke.uang.bean.IdentityData;
import com.jinke.uang.bean.ImgsListData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.camera.CameraPhotoActivity;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.permission.IPermisson;
import com.jinke.uang.permission.Permission;
import com.jinke.uang.utils.FileUtils;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.utils.systemutil.UploadImageUtil;
import com.jinke.uang.utils.toolutil.ImageUtils;
import com.jinke.uang.view.SelectImgDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 其他补充资料认证
 */
@SuppressLint("CheckResult")
@Route(name = "其他补充资料认证", path = RouterMap.PHOTO_AUTH_PAGE)
public class PhotoAuthActivity extends BaseNormalActivity<CommonPresenter,AuthModule> implements IPermisson, SelectImgDialog.SelectImgDialogClickListener {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tvNext)
    TextView tvNext;
    private OtherAdapter adapter;
    private List<ImgsListData.ImgPathListBean> data = new ArrayList<>();
    private int mClickGridItemPosition;
    private Permission permission;
    private String ADDITIONAL_INFORMATION_CODE="additional_information_code";

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        topBack.setOnClickListener(viewclick);
        //获取头部信息
        topText.setText(getStringResource(R.string.custom_auth_page_title));
        tvNext.setOnClickListener(viewclick);

        GridLayoutManager gl = new GridLayoutManager(this, 3);
        initGridData();
        adapter = new OtherAdapter(this, data);
        rv.setLayoutManager(gl);
        rv.setAdapter(adapter);
        rv.setItemViewCacheSize(0);
        adapter.setOnItemClickListener(new OtherAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                permission.uploadImage(position);
            }
        });
    }

    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.topBack:
                    finish();
                    break;
                case R.id.tvNext:
                    commit();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 提交
     */
    private void commit() {
        mPresenter.getData(HttpConstant.SAVE_ADD_INFORMATION,null,ADDITIONAL_INFORMATION_CODE,imageInfoParams);
        showLoadingView();
    }

    @Autowired(name = Constant.IS_BACK)
    boolean is_back;

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);

        permission = new Permission(this, this);
        GridLayoutManager gl = new GridLayoutManager(this, 3);
        rv.setLayoutManager(gl);
        if (UserInfo.isShowUserInformation()) {
            mPresenter.getData(HttpConstant.AUTH_INFO_DATA,null,ADDITIONAL_INFORMATION_CODE);
        }
        if (is_back) {
            tvNext.setText(R.string.save_change);
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_photo;
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    public String getPageTitle() {
        return null;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected AuthModule getModule() {
        return new AuthModule();
    }

    public void initGridData() {
        data.clear();
        for (int i = 0; i < 10; i++) {
            ImgsListData.ImgPathListBean bean = new ImgsListData.ImgPathListBean();
            bean.setImageType(i + 3);
            data.add(bean);
        }
    }

    /**
     * 打开相机
     *
     * @param position
     */
    private void openTakePhoto(final int position) {
        Intent intent = new Intent(this, CameraPhotoActivity.class);
        startActivityForResult(intent, position);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent ondata) {
        super.onActivityResult(requestCode, resultCode, ondata);
        if (requestCode >= 0 && requestCode <= 9) {
            if (null != ondata) {
                final String filePath = ondata.getStringExtra("filename");
                File file = new File(filePath);
                if (0 == file.length()) {
                    //设置图片的
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                    if (null != bitmap && bitmap.getAllocationByteCount() > 0) {
                        bitmap = UploadImageUtil.getUploadNeedBitmapBYSize(bitmap);
                        byte[] bitmapByte = ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.JPEG);
                        mPresenter.getData(HttpConstant.BITMAP_UPLOAD_SINGLE_IMG,null,requestCode + 3,bitmapByte);
                        dismissLoadingView();
                        ImgsListData.ImgPathListBean bean = data.get(requestCode);
                        bean.setNativeFileUri(Uri.fromFile(file));
                        data.set(requestCode, bean);
                        adapter.notifyItemChanged(requestCode);
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                compressImgAndDisPlayForFileString(filePath, Constant
                                        .PIC_TYPE_ID_CARD_POSITIVE);
                            }
                        }, 1500);
                    }
                } else {
                    //设置图片的
                    compressImgAndDisPlay(file, requestCode);
                    ImgsListData.ImgPathListBean bean = data.get(requestCode);
                    bean.setNativeFileUri(Uri.fromFile(file));
                    data.set(requestCode, bean);
                    adapter.notifyItemChanged(requestCode);
                }
            }
        }
    }

    @Override
    public void onTakePhotoClick() {
        openTakePhoto(mClickGridItemPosition);
    }

    @Override
    public void onSelectPictureClick() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media
                .EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, mClickGridItemPosition + 12);
    }

    /**
     * 压缩并上传图片
     *
     * @param file
     * @param compressType
     */
    public void compressImgAndDisPlay(final File file, final int compressType) {
        //FileUtils.getCompressedPath()
        Luban.with(this).ignoreBy(500).load(file).setTargetDir(FileUtils.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                mPresenter.getData(HttpConstant.UPLOAD_SINGLE_IMG,null,compressType + 3, file);
                dismissLoadingView();
                ImgsListData.ImgPathListBean bean = data.get(compressType);
                bean.setNativeFileUri(Uri.fromFile(file));
                data.set(compressType, bean);
                adapter.notifyItemChanged(compressType);
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();
    }

    public void compressImgAndDisPlayForFileString(final String file, final int compressType) {
        Luban.with(this).ignoreBy(500).load(file).setTargetDir(FileUtils.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                mPresenter.getData(HttpConstant.UPLOAD_SINGLE_IMG,null,compressType + 3, file);
                dismissLoadingView();
                ImgsListData.ImgPathListBean bean = data.get(compressType);
                bean.setNativeFileUri(Uri.fromFile(file));
                data.set(compressType, bean);
                adapter.notifyItemChanged(compressType);
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();
    }


    @Override
    public void onSuccess(int result) {
        mClickGridItemPosition = result;
        openTakePhoto(mClickGridItemPosition);
    }

    @Override
    public void onSuccess(Object object) {}

    private List<IdentityData.ImageInfoBean> imageInfoParams = new ArrayList<>();

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        dismissLoadingView();
        if(apiType== HttpConstant.UPLOAD_SINGLE_IMG){ //上传图片接口
            BaseResponse<IdentityData> identityResponse = (BaseResponse<IdentityData>) o;
            if (identityResponse.getStatus() != Constant.HTTP_OK) {
                ToastUtils.showShort(PhotoAuthActivity.this, identityResponse.getMessage());
                return;
            }
            for (IdentityData.ImageInfoBean bean : imageInfoParams) {
                if (bean.getFileType() == identityResponse.getData().getImageInfo().getFileType()) {
                    imageInfoParams.remove(bean);
                    imageInfoParams.add(identityResponse.getData().getImageInfo());
                    return;
                }
            }
            imageInfoParams.add(identityResponse.getData().getImageInfo());
        }

        else if(apiType==HttpConstant.AUTH_INFO_DATA){  //图片信息认证
            BaseResponse<AuthUserInfoData> response = (BaseResponse<AuthUserInfoData>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                List<AuthUserInfoData.AdditionalInformationBean.ImageListBean> imageList = response
                        .getData().getAdditionalInformation().getImageList();
                if (imageList == null || imageList.size() == 0) {
                    return;
                }
                for (int i = 0; i < imageList.size(); i++) {
                    ImgsListData.ImgPathListBean bean = new ImgsListData.ImgPathListBean();
                    bean.setImageType(imageList.get(i).getFileType());
                    bean.setImagePathUrl(imageList.get(i).getImageUrl());
                    switch (bean.getImageType()) {
                        case 3:
                            data.set(0, bean);
                            break;
                        case 4:
                            data.set(1, bean);
                            break;
                        case 5:
                            data.set(2, bean);
                            break;
                        case 6:
                            data.set(3, bean);
                            break;
                        case 7:
                            data.set(4, bean);
                            break;
                        case 8:
                            data.set(5, bean);
                            break;
                        case 9:
                            data.set(6, bean);
                            break;
                        case 10:
                            data.set(7, bean);
                            break;
                        case 11:
                            data.set(8, bean);
                            break;
                        case 12:
                            data.set(9, bean);
                            break;
                        default:
                            break;
                    }
                    imageInfoParams.clear();
                    for (AuthUserInfoData.AdditionalInformationBean.ImageListBean imageListBean :
                            response.getData().getAdditionalInformation().getImageList()) {

                        IdentityData.ImageInfoBean infoBean = new IdentityData.ImageInfoBean();
                        infoBean.setImageName(imageListBean.getImageName());
                        infoBean.setFileType(imageListBean.getFileType());
                        infoBean.setImagePath(imageListBean.getImagePath());
                        infoBean.setImageUrl(imageListBean.getImageUrl());
                        imageInfoParams.add(infoBean);
                    }
                }
                adapter.notifyDataSetChanged();
            } else {
                ToastUtils.showShort(PhotoAuthActivity.this, response.getMessage());
            }
        }

        else if(apiType==HttpConstant.SAVE_ADD_INFORMATION){ //其他图片认证接口
            dismissLoadingView();
            if (!is_back) {
                UserAuthRouter.getInstance().jumpNextPager(PhotoAuthActivity.this, RouterMap
                        .PHOTO_AUTH_PAGE);
            } else {
                finish();
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
        ToastUtils.showShort(this, R.string.network_error);
    }
}
